package Lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * @author : <h2>冷环渊</h2>
 * @date : 2021/12/11
 * @context: <h4>
 * 消费型接口 Consumer<T> Accept(T t)
 * 供给型接口 Supplier<T> T get()
 * 函数式接口 Function<T> R apply(T t)
 * 断定型接口 Predicate<T> boolean test(T t)
 * </h4>
 */
public class LambdaTest2 {


    /**
     * @author 冷环渊 Doomwatcher
     * @context: Consumer<T> 使用
     * @date: 2021/12/11 14:37
     * @param
     * @return: void
     */
    @Test
    public void Test1() {
        happyTime(500, new Consumer<Double>() {
            @Override
            public void accept(Double aDouble) {
                System.out.println("天上人间的水今天很贵：" + aDouble);
            }
        });
        System.out.println("****************************");
        happyTime(400, money -> System.out.println("学习太累了，去天上人间买了瓶矿泉水，价格为：" + money));
    }

    /**
     * @author: 冷环渊 Doomwatcher
     * @context:
     * @date: 2021/12/11 14:33
     * @param money
     * @param con
     * @return void
     */
    public void happyTime(double money, Consumer<Double> con) {

        con.accept(money);
    }

    /**
     * @author 冷环渊 Doomwatcher
     * @context: 断言 Predicate 的使用
     * @date: 2021/12/11 14:39
     * @param
     * @return: void
     */
    @Test
    public void Test2() {
        //传统写法
        List<String> filterList = Arrays.asList("北京", "天津", "南京", "东京", "江南");
        List<String> filterStr = filterString(filterList, new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.contains("京");
            }
        });
        System.out.println(filterStr);
        System.out.println("*******************************");
        // Lambda表达式 写法
        List<String> filterList1 = Arrays.asList("北京", "天津", "南京", "东京", "江南");
        List<String> filterStr1 = filterString(filterList1, s -> s.contains("京"));
        System.out.println(filterStr1);
    }


    /**
     * @author 冷环渊 Doomwatcher
     * @context:
     * @date: 2021/12/11 21:51
     * @param list
     * @param pre
     * @return: java.util.List<java.lang.String>
     */
    public List<String> filterString(List<String> list, Predicate<String> pre) {
        ArrayList<String> filterlist = new ArrayList<>();
        for (String s : list) {
            if (pre.test(s)) {
                filterlist.add(s);
            }
        }
        return filterlist;
    }
}
